package com.anche.cywebnew.Service.auditManager.impl;

import com.anche.cywebnew.DAO.auditManager.LoginLogMapper;
import com.anche.cywebnew.DAO.configManager.SysOptionMapper;
import com.anche.cywebnew.Pojo.auditManager.LogInfo;
import com.anche.cywebnew.Service.auditManager.LoginLogSercive;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.log4j.Log4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j
public class LoginLogSerciveImpl implements LoginLogSercive {

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
    private SysOptionMapper sysOptionMapper;

    @Override
    public Page<LogInfo> getLoginLogPager(Integer page, Integer limit, LogInfo logInfo) {
        Page<LogInfo> page1 = PageHelper.startPage(page, limit);
        List<LogInfo> logInfos = loginLogMapper.selectLoginLogList(logInfo);
        for (LogInfo log : logInfos) {
            String jyw = DigestUtils.md5Hex(log.getUser_id() + log.getOperate_type() + log.getOperate_time() + log.getOperate_result());
            if (!jyw.equals(log.getJyw())){
                log.setIsupdate(1);
            }
        }
        return page1;
    }

    @Override
    public List<Map<String, String>> getLoginLogStat() {
        return loginLogMapper.selectLoginLogStat(null, null);
    }


    @Override
    public Map<String, String> checkHeightFW(String terminal_id){
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat spf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fwsx = sysOptionMapper.getOptionValue("安全策略", "highLogin", "1");
        fwsx = fwsx == null ? "10" : fwsx;
        Integer ifwsx = 10;
        try {
            ifwsx = Integer.parseInt(fwsx);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("高频访问配置值必须为整型", e);
        }
        Date endDate = new Date();
        String endDates = spf.format(endDate);
        String beginDates = spf.format(new Date(endDate.getTime() - 60 * 60 * 1000));
        int count = loginLogMapper.selectLoginLogCount(beginDates, endDates, terminal_id);
        if (count >= ifwsx) {
            map.put("code", "0");
            map.put("msg", "高频访问,超出访问上限");
        }else {
            map.put("code", "1");
            map.put("msg", "");
        }
        return map;
    }
}
